package com.vtron.core;

import lombok.Data;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @网络请求结果集
 * @date : 2021/12/30 9:06
 * @author: 忻龙彪
 */
@Data
public class HttpResult implements Serializable {
    /**
     * 状态码[200:成功]
     */
    public Integer status;
    /**
     * 结果描述
     */
    public String message;
    /**
     * 结果对象
     */
    public Object data;
    /**
     * 时间戳
     */
    public String timestamp;

    public HttpResult() {
        this.status = HttpCode.SUCCESS.getValue();
        this.message = HttpCode.SUCCESS.getDesc();
        this.timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    public HttpResult(Object data) {
        this();
        this.data = data;
    }

    public HttpResult(HttpCode status, String msg) {
        this();
        this.status = status.getValue();
        this.message = msg;
    }

    public HttpResult(IHttpResultBuild action) {
        this(action, "服务接口异常");
    }

    public HttpResult(IHttpResultBuild action, String msg) {
        this();
        try {
            this.data = action.build();
        } catch (Throwable ex) {
            this.status = HttpCode.SERVER_ERROR.getValue();
            this.message = msg;
            if (isEmpty(this.message)) {
                this.message = ex.getMessage();
            }
        }
    }

    private boolean isEmpty(String temp) {

        boolean b = true;
        if (Objects.nonNull(temp)) {
            temp = temp.toLowerCase().trim();
            b = "null".equals(temp) || "undefined".equals(temp) || temp.length() <= 0;
        }
        return b;
    }

}
